﻿using PetaPoco.Internal;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System.Runtime.Caching;

namespace Cxuu.Common
{
    public class MemoryCacheManager : ICacheManager
    {
        private readonly string cacheMainName = Appsettings.App(new string[] { "AppSettings", "SystemName" }) + ".";

        public MemoryCacheManager() { }


        public ObjectCache cache = MemoryCache.Default;//声明缓存类

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="name">缓存的名字</param>
        /// <param name="Ovlaue">需要缓存的值</param>
        /// <param name="seconds">过期时间</param>
        public void Set(string name, object Ovlaue, TimeSpan cacheTime)
        {
            CacheItemPolicy policy = new();

            policy.SlidingExpiration = cacheTime;
            if (!string.IsNullOrEmpty(name) && (Ovlaue != null))
            {
                cache.Set(name, Ovlaue, policy);
            }
        }

        /// <summary>
        ///缓存是存在否，传入缓存名字即可
        /// </summary>
        /// <param name="name">缓存的名字</param>
        /// <returns></returns>
        public bool Get(string name)
        {
            if ((string)cache[name] != null)
                return true;
            else
                return false;

        }

        /// <summary>
        /// 获取缓存KEY根名实现方法
        /// </summary>
        /// <returns></returns>
        public string CacheName()
        {
            return cacheMainName;
        }



        public string GetValue(string key)
        {
            try
            {
                return (string)cache[key];
            }
            catch (Exception)
            {
                return null;
            }


        }

        public TEntity Get<TEntity>(string key)
        {
            try
            {
                return (TEntity)cache[key];
            }
            catch (Exception)
            {
                return default;
            }
        }

        public bool Clear()
        {
            return false;
        }




        public bool Remove(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
           // key = key.ToLower();
           // var del = cache.Remove(key);
            if (cache.Remove(key) != null)
                return true;
            else
                return false;
        }


        public void RemoveCacheAsync(string cacheKey)
        {
            cache.Remove(cacheKey);
        }


        public long TotalNumber()
        {
            return cache.GetCount();
        }

    }
}
